package com.ruoyi.weixin.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.mail.EmailUtils;
import com.ruoyi.framework.util.RedisUtils;
import com.ruoyi.weixin.domain.Client;
import com.ruoyi.weixin.mapper.ClientMapper;
import com.ruoyi.weixin.service.IWxService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WxServiceImpl implements IWxService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private ClientMapper clientMapper;


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private EmailUtils emailUtils;


    public Client login(String code, String encryptedData, String iv) throws WxErrorException {
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        Client client = null;
        if (StringUtils.isNotEmpty(session.getOpenid())){
            Client c = new Client();
            c.setOpenId(session.getOpenid());
            client = clientMapper.selectClientInfoById(c);
            return client;
        }
        if (client == null){
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), encryptedData, iv);
            client = new Client();
            client.setAvatarUrl(userInfo.getAvatarUrl());
            client.setCity(userInfo.getCity());
            client.setClientId(UUID.randomUUID().toString().replace("-",""));
            client.setConuntry(userInfo.getCountry());
            client.setGender(userInfo.getGender());
            client.setJoinDate(new Date());
            client.setProvince(userInfo.getProvince());
            client.setNickName(userInfo.getNickName());
            client.setOpenId(userInfo.getOpenId());
            client.setUnionId(userInfo.getUnionId());
            clientMapper.insertClient(client);
        }
        return clientMapper.selectClientInfoById(client);
    }

    @Override
    public Client wxPhone(String clientId, String code, String encryptedData, String iv) throws WxErrorException {
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
        Client client = new Client();
        client.setPhone(phoneNoInfo.getPhoneNumber());
        client.setClientId(clientId);
        clientMapper.updateClient(client);
        client = clientMapper.selectClientById(client);
        return client;
    }

    @Override
    public String emailVerifi(String clientId, String email) {
        Random random = new Random();
        String verifi = random.nextInt(1000000) + "";
        Map<String, String> map = new HashMap<String, String>();
        map.put(email, verifi);
        if (redisUtils.hasKey(clientId)){
            redisUtils.del(clientId);
        }
        redisUtils.set(clientId, map, 600);
        emailUtils.sendSimpleMail(email, "验证码", "请在10分钟内输入验证码：" + verifi + ",请勿泄露验证码，如有疑问请停止操作");
        return null;
    }

    @Override
    public boolean emailBinding(String clientId, String email, String verifi) {
        Map map = (Map) redisUtils.get(clientId);
        if (verifi.equals(map.get(email))){
            Client client = new Client();
            client.setClientId(clientId);
            client.setEmail(email);
            clientMapper.updateClient(client);
            redisUtils.del(clientId);
            return true;
        }
        return false;
    }
}
